package com.hliushi.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;

/**
 * @author llhuang10
 * @date 2021/7/23 18:17
 */
@RestController
@RequestMapping("/api")
public class FileDownResource {


    @GetMapping(value = "/downloadExcel", consumes = MediaType.ALL_VALUE)
    public void downloadExcel(final HttpServletResponse response) throws Exception {

        String name = "测试." + ExcelTypeEnum.XLSX;
        // 清空缓冲区，状态码和响应头(headers)
        response.reset();
        // 设置ContentType，响应内容为文本数据，编码为utf-8，此处设定的编码是文件内容的编码
        response.setContentType("text/plain;charset=utf-8");
        // 以（Content-Disposition: attachment; filename="filename.jpg"）格式设定默认文件名，设定utf编码，此处的编码是文件名的编码，使能正确显示中文文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + name + ";filename*=utf-8''" + URLEncoder.encode(name, "utf-8"));

        // 响应输出流
        OutputStream out = response.getOutputStream();
        // 建立excel
        ExcelWriter excelWriter = EasyExcel.write(out).build();
        // 建立sheet
        WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
        // 指定sheet并写数据
        excelWriter.write(getListString(), writeSheet);
        // 不要忘记
        excelWriter.finish();
        out.flush();
    }


    /**
     * 生成excel内容
     *
     * @return
     */
    public List<List<String>> getListString() {
        List<List<String>> result = new LinkedList<>();
        List<String> data1 = new LinkedList<>();
        data1.add("1");
        data1.add("张三");
        data1.add("北京");
        result.add(data1);
        List<String> data2 = new LinkedList<>();
        data2.add("2");
        data2.add("李四");
        data2.add("上海");
        result.add(data2);
        List<String> data3 = new LinkedList<>();
        data3.add("3");
        data3.add("王五");
        data3.add("广州");
        result.add(data3);
        return result;
    }

}
